﻿namespace YK.Console.Business.PackagePermissionGroups;

internal class SavePackagePermissionGroupHandler(IRepository<PackagePermissionGroup> _repo) : IRequestHandler<SavePackagePermissionGroupRequest, bool>
{
    public async Task<bool> Handle(SavePackagePermissionGroupRequest request, CancellationToken cancellationToken)
    {
        await _repo.DeleteAsync(x => x.PackageId == request.PackageId, cancellationToken);

        if (request.PermissionGroupIds.Any())
        {
            var pkgPermissionGourps = request.PermissionGroupIds.Select(x => new PackagePermissionGroup
            {
                PackageId = request.PackageId,
                PermissionGroupId = x
            }).ToList();

            await _repo.AddRangeAsync(pkgPermissionGourps, cancellationToken);
        }
        return true;
    }
}


internal class PkgPermissionGroupSearchByPkgIdsHandler(IReadRepository<PackagePermissionGroup> _repo) 
    : IRequestHandler<PkgPermissionGroupSearchByPkgIdsRequest, List<PackagePermissionGroupOutput>>
{
    public Task<List<PackagePermissionGroupOutput>> Handle(PkgPermissionGroupSearchByPkgIdsRequest request, CancellationToken cancellationToken)
        => _repo.SimpleListAsync<PackagePermissionGroupOutput>(x => request.PackageIds.Contains(x.PackageId) && x.PermissionGroup.Enabled == EnabledStatusEnum.Enabled, cancellationToken);
}
